package com.app.oral.model

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import java.math.BigDecimal
import java.time.LocalDateTime

/**
 * 练习记录模型 - JSON优化结构（与docs一致）
 */
data class ExerciseRecord(
    val id: String,
    val userId: Long,
    val paperId: Long,
    val mode: ExerciseMode,

    // 状态与位置
    val status: ExerciseStatus = ExerciseStatus.NOT_STARTED,
    val currentStage: ExerciseStage = ExerciseStage.READING,
    val currentQuestionIndex: Int = 0,

    // JSON 答题数据
    val readingAnswer: ReadingAnswer? = null,
    val dialogueAnswers: List<QuestionAnswer> = emptyList(),
    val listeningAnswers: List<QuestionAnswer> = emptyList(),
    val expressionAnswer: ExpressionAnswer? = null,

    // 总分与时间
    val totalScore: BigDecimal? = null,
    val createdAt: LocalDateTime = LocalDateTime.now(),
    val updatedAt: LocalDateTime = LocalDateTime.now(),
    val completedAt: LocalDateTime? = null
) {
    // 计算属性
    fun isCompleted(): Boolean = status == ExerciseStatus.COMPLETED

    fun getProgressPercentage(): Int {
        val completedCount =
            (if (readingAnswer?.completed == true) 1 else 0) +
                dialogueAnswers.count { it.completed } +
                listeningAnswers.count { it.completed } +
                (if (expressionAnswer?.completed == true) 1 else 0)
        return (completedCount * 100) / 12
    }

    fun parseReadingScoreDetails(): ReadingScoreDetails? = readingAnswer?.scoreDetails
    fun parseExpressionScoreDetails(): ExpressionScoreDetails? = expressionAnswer?.scoreDetails

    fun withReadingScoreDetails(scoreDetails: ReadingScoreDetails): ExerciseRecord {
        val updated = (readingAnswer ?: ReadingAnswer()).copy(scoreDetails = scoreDetails)
        return this.copy(readingAnswer = updated)
    }

    fun withExpressionScoreDetails(scoreDetails: ExpressionScoreDetails): ExerciseRecord {
        val updated = (expressionAnswer ?: ExpressionAnswer()).copy(scoreDetails = scoreDetails)
        return this.copy(expressionAnswer = updated)
    }

    fun extractAllAudioFileIds(): List<String> {
        val list = mutableListOf<String>()
        readingAnswer?.audioFileId?.let { if (it.isNotEmpty()) list.add(it) }
        dialogueAnswers.mapNotNull { it.audioFileId }.filter { it.isNotEmpty() }.let { list.addAll(it) }
        listeningAnswers.mapNotNull { it.audioFileId }.filter { it.isNotEmpty() }.let { list.addAll(it) }
        expressionAnswer?.audioFileId?.let { if (it.isNotEmpty()) list.add(it) }
        return list.distinct()
    }
}

// JSON结构元素
@JsonIgnoreProperties(ignoreUnknown = true)
data class ReadingAnswer(
    val completed: Boolean = false,
    val audioFileId: String? = null,
    val scoreDetails: ReadingScoreDetails? = null,
    val attemptTime: LocalDateTime? = null
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class QuestionAnswer(
    val number: Int,
    val completed: Boolean = false,
    val audioFileId: String? = null,
    val score: BigDecimal? = null,
    val attemptTime: LocalDateTime? = null
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class ExpressionAnswer(
    val completed: Boolean = false,
    val audioFileId: String? = null,
    val score: BigDecimal? = null,
    val scoreDetails: ExpressionScoreDetails? = null,
    val attemptTime: LocalDateTime? = null
)

// 状态与阶段
enum class ExerciseStatus(val value: String, val displayName: String) {
    NOT_STARTED("not_started", "未开始"),
    IN_PROGRESS("in_progress", "进行中"),
    COMPLETED("completed", "已完成")
}

enum class ExerciseStage(val value: String, val displayName: String, val order: Int) {
    READING("reading", "短文朗读", 1),
    LISTENING("listening", "视听应答", 2),
    DIALOGUE("dialogue", "情景问答", 3),
    EXPRESSION("expression", "话题简述", 4)
}

// 评分详情仍保留
@JsonIgnoreProperties(ignoreUnknown = true)
data class ReadingScoreDetails(
    val accuracy: BigDecimal,
    val fluency: BigDecimal,
    val completeness: BigDecimal,
    val suggestedScore: BigDecimal,
    val wordMatches: WordMatches? = null
)
